<?php

namespace App\Controller\Home;

use App\Controller\Example\SettlementExample;
use App\Controller\Example\ShopGoodsExample;
use App\Controller\Example\ShopGoodsOrderExample;
use App\Controller\Example\ShopGoodsSkuExample;
use App\Controller\Example\UserAddrExample;
use App\Controller\Example\UserExample;
use App\Models\ConfigModel;
use App\Models\Conn;
use App\Models\CtcSettingModel;
use App\Models\SettlementModel;
use App\Models\ShopGoodsModel;
use App\Models\ShopGoodsOrderModel;
use App\Models\ShopGoodsSkuModel;
use App\Models\UsersAddrModel;
use App\Models\UsersModel;
use App\Models\WinningModel;
use Core\Common\Common;
use Core\Enums\DigitEnum;
use Core\Enums\ErrorEnum;
use Core\Enums\FundsEnum;
use Core\Result\Result;
use Core\Utils\Utils;

class Pay
{
    /**
     * TODO 商品订单余额支付（消费积分）
     * @param $data pay_password address_id sku_id order_number remark
     * @return void
     */
    function orderBalanceBuy($data){
        Result::error("暂未开放接口");
        $assemble = Common::assemble(new ShopGoodsOrderExample(), $data);
        $pay_password=$data['pay_password'];
        $address_id=$data['address_id'];
        if($assemble->order_number <= DigitEnum::ZERO){
            Result::error(ErrorEnum::THISORDERHASEXPIRED[$assemble->language]);
        }
        if($address_id <= DigitEnum::ZERO){
            Result::error(ErrorEnum::PLEASESELECTSHIPPINGADDRESS[$assemble->language]);
        }
        if($assemble->sku_id <= DigitEnum::ZERO){
            Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        }
        $conn = new Conn();
        $UserPassword = UsersModel::getUserPasswordInside($conn, $assemble->token);
        if($UserPassword["pay_password"] == null){
            Result::error(ErrorEnum::PLEASESETASECONDLEVELPAYMENTPASSWORD[$assemble->language]);
        }
        if($UserPassword["pay_password"] != md5(md5($pay_password))){
            Result::error(ErrorEnum::SECONDLEVELPAYMENTPASSWORDERROR[$assemble->language]);
        }
        $goodsSkuInfo = Common::assemble(new ShopGoodsSkuExample(),ShopGoodsSkuModel::getGoodsSkuInfo($conn, $assemble->sku_id));
        if($goodsSkuInfo->sku_stock < $assemble->order_number){
            Result::error(ErrorEnum::INSUFFICIENTINVENTORY[$assemble->language]);
        }
        $goodsSkuInfo->sku_stock = $goodsSkuInfo->sku_stock - $assemble->order_number;//减去库存
        if($goodsSkuInfo->sku_stock == 0){
            $goodsSkuInfo->sku_stock = '0';
        }
        $ShopGoodsExample = Common::assemble(new ShopGoodsExample(), ShopGoodsModel::getGoodsInfo($conn, $goodsSkuInfo->goods_id));
        if($ShopGoodsExample->is_top == DigitEnum::ZERO || $ShopGoodsExample->is_adopt == DigitEnum::ZERO){
            Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        }
        $UserExample = Common::assemble(new UserExample(), UsersModel::getUserInside($conn, $assemble->token));
        $consult_price = CtcSettingModel::getCtcSettingInit($conn, 2)["consult_price"];
        $assemble->merchant_id = $ShopGoodsExample->merchant_id;
        $assemble->goods_id = $ShopGoodsExample->goods_id;
        $assemble->order_price = $goodsSkuInfo->sku_sell_price;
        $settlementExample = new SettlementExample();
        $userAddrExample = new UserAddrExample();
        $settlementExample->cost = $goodsSkuInfo->sku_cost_price * $assemble->order_number;
        $assemble->order_total_price = round($goodsSkuInfo->sku_sell_price / $consult_price,2) * $assemble->order_number;//已换算金本位
        $settlementExample->money = $goodsSkuInfo->sku_sell_price * $assemble->order_number;
        $userAddrExample->id = $address_id;
        $settlementExample->uid = $assemble->member_id = $userAddrExample->uid = $UserExample->id;
        $assemble->type = $settlementExample->type = DigitEnum::ONE;
        $userAddr = UsersAddrModel::getUserAddr($conn, $userAddrExample);
        if (!$userAddr){
            Result::error(ErrorEnum::DELIVERYADDRESSDOESNOTEXIST[$assemble->language]);
        }
        $balance = $UserExample->money - $assemble->order_total_price;
        if($assemble->order_total_price <= DigitEnum::ZERO || $UserExample->money <= DigitEnum::ZERO || $balance < DigitEnum::ZERO){
            Result::error(ErrorEnum::INSUFFICIENTBALANCE[$assemble->language]);
        }
        $assemble->receipt_name = $userAddr["name"];
        $assemble->receipt_phone = $userAddr["mobile"];
        $assemble->receipt_address = $userAddr["detailed_address"];
        $settlementExample->no = $assemble->order_no ="xf".Utils::createOrderNo();
        $svip = 1;
        $shopGoodsExample = new ShopGoodsExample();
        $shopGoodsExample->goods_id = $ShopGoodsExample->goods_id;
        $shopGoodsExample->sales_volume = $ShopGoodsExample->sales_volume + $assemble->order_number;
        $conn->shiwuStart();
        $insertSettlementInside = SettlementModel::insertSettlementInside($conn, $settlementExample);
        $SettlementId = $conn->mysql_insert_id();
        $insertShopGoodsOrderInside = ShopGoodsOrderModel::insertShopGoodsOrderInside($conn, $assemble);
        $upShopGoodsSkuInside = ShopGoodsSkuModel::upshopGoodsSkuInside($conn, $goodsSkuInfo);
        $editUserMoneyOutInside = UsersModel::editUserMoneyAndCappingInside($conn, $assemble->order_total_price,$settlementExample->money,$svip,$UserExample);
        $writeFundsMoney = Funds::writeFundsMoney($conn, $UserExample->id, $assemble->order_no, FundsEnum::PLACEANORDERPURCHASE, -$assemble->order_total_price, $balance, FundsEnum::PLACEANORDERPURCHASEZHCN);
        $upShopGoodsInside = ShopGoodsModel::upShopGoodsInside($conn, $shopGoodsExample);
        if($insertSettlementInside != DigitEnum::ONE || $insertShopGoodsOrderInside != DigitEnum::ONE || $upShopGoodsSkuInside != DigitEnum::ONE || $editUserMoneyOutInside != DigitEnum::ONE || $writeFundsMoney != DigitEnum::ONE || $upShopGoodsInside != DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::ORDERPLACEMENTFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        //Sett::customers($SettlementId);
        Sett::settlement($UserExample->pid,$SettlementId,$settlementExample->money,$settlementExample->no);
        Result::success(ErrorEnum::PAYMENTSUCCESSFUL[$assemble->language]);
    }
    /**
     * TODO 商品订单余额支付（无忧积分）
     * @param $data pay_password address_id sku_id order_number remark
     * @return void
     */
    function orderLingLongBuy($data){
        $time = time();
        $startTime = strtotime(date('Y-m-d') . ' 00:00:00');
        $endTime = strtotime(date('Y-m-d') . ' 00:30:00');
        if ($time >= $startTime && $time <= $endTime){
            Result::error('系统结算时间，请0:30:01再操作！');
        }
        $assemble = Common::assemble(new ShopGoodsOrderExample(), $data);
        $pay_password=$data['pay_password'];
        $address_id=$data['address_id'];
        if($assemble->order_number <= DigitEnum::ZERO){
            Result::error(ErrorEnum::THISORDERHASEXPIRED[$assemble->language]);
        }
        if($address_id <= DigitEnum::ZERO){
            Result::error(ErrorEnum::PLEASESELECTSHIPPINGADDRESS[$assemble->language]);
        }
        if($assemble->sku_id <= DigitEnum::ZERO){
            Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        }
        $conn = new Conn();
        $UserPassword = UsersModel::getUserPasswordInside($conn, $assemble->token);
        if($UserPassword["pay_password"] == null){
            Result::error(ErrorEnum::PLEASESETASECONDLEVELPAYMENTPASSWORD[$assemble->language]);
        }
        if($UserPassword["pay_password"] != md5(md5($pay_password))){
            Result::error(ErrorEnum::SECONDLEVELPAYMENTPASSWORDERROR[$assemble->language]);
        }
        $goodsSkuInfo = Common::assemble(new ShopGoodsSkuExample(),ShopGoodsSkuModel::getGoodsSkuInfo($conn, $assemble->sku_id));
        if($goodsSkuInfo->sku_stock < $assemble->order_number){
            Result::error(ErrorEnum::INSUFFICIENTINVENTORY[$assemble->language]);
        }
        $goodsSkuInfo->sku_stock = $goodsSkuInfo->sku_stock - $assemble->order_number;//减去库存
        if($goodsSkuInfo->sku_stock == 0){
            $goodsSkuInfo->sku_stock = '0';
        }
        $ShopGoodsExample = Common::assemble(new ShopGoodsExample(), ShopGoodsModel::getGoodsInfo($conn, $goodsSkuInfo->goods_id));
        if($ShopGoodsExample->is_top == DigitEnum::ZERO || $ShopGoodsExample->is_adopt == DigitEnum::ZERO){
            Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        }
        $UserExample = Common::assemble(new UserExample(), UsersModel::getUserInside($conn, $assemble->token));
        $assemble->merchant_id = $ShopGoodsExample->merchant_id;
        $assemble->goods_id = $ShopGoodsExample->goods_id;
        $assemble->order_price = $goodsSkuInfo->sku_sell_price;
        $multiple = ConfigModel::getConfigSingleValName($conn, "multiple");
        if($multiple < 0){
            Result::error("奖励倍数配置出错");
        }
        $settlementExample = new SettlementExample();
        $userAddrExample = new UserAddrExample();
        $settlementExample->money = $assemble->order_total_price = $goodsSkuInfo->sku_sell_price * $assemble->order_number;
        $settlementExample->cost = $settlementExample->total = $settlementExample->money * $multiple;
        $userAddrExample->id = $address_id;
        $settlementExample->uid = $assemble->member_id = $userAddrExample->uid = $UserExample->id;
        $assemble->type = $settlementExample->type = DigitEnum::ONE;
        $userAddr = UsersAddrModel::getUserAddr($conn, $userAddrExample);
        if (!$userAddr){
            Result::error(ErrorEnum::DELIVERYADDRESSDOESNOTEXIST[$assemble->language]);
        }
        $balance = $UserExample->usdt - $assemble->order_total_price;
        if($assemble->order_total_price <= DigitEnum::ZERO || $UserExample->usdt <= DigitEnum::ZERO || $balance < DigitEnum::ZERO){
            Result::error(ErrorEnum::INSUFFICIENTBALANCE[$assemble->language]);
        }
        $assemble->receipt_name = $userAddr["name"];
        $assemble->receipt_phone = $userAddr["mobile"];
        $assemble->receipt_address = $userAddr["detailed_address"];
        $settlementExample->no = $assemble->order_no = "wy".Utils::createOrderNo();
        $svip = 1;
        $shopGoodsExample = new ShopGoodsExample();
        $shopGoodsExample->goods_id = $ShopGoodsExample->goods_id;
        $shopGoodsExample->sales_volume = $ShopGoodsExample->sales_volume + $assemble->order_number;
        $conn->shiwuStart();
        $insertSettlementInside = SettlementModel::insertSettlementInside($conn, $settlementExample);
        $SettlementId = $conn->mysql_insert_id();
        $insertShopGoodsOrderInside = ShopGoodsOrderModel::insertShopGoodsOrderInside($conn, $assemble);
        $upShopGoodsSkuInside = ShopGoodsSkuModel::upshopGoodsSkuInside($conn, $goodsSkuInfo);
        $capping = $assemble->order_total_price * $multiple;
        $editUserMoneyOutInside = UsersModel::editUserUsdtAndCappingInside($conn, $assemble->order_total_price,$settlementExample->money,$svip,$capping,$UserExample);
        $writeFundsMoney = Funds::writeFundsUsdt($conn, $UserExample->id, $assemble->order_no, FundsEnum::PLACEANORDERPURCHASE, -$assemble->order_total_price, $balance, FundsEnum::PLACEANORDERPURCHASEZHCN);
        $upShopGoodsInside = ShopGoodsModel::upShopGoodsInside($conn, $shopGoodsExample);
        if($insertSettlementInside != DigitEnum::ONE || $insertShopGoodsOrderInside != DigitEnum::ONE || $upShopGoodsSkuInside != DigitEnum::ONE || $editUserMoneyOutInside != DigitEnum::ONE || $writeFundsMoney != DigitEnum::ONE || $upShopGoodsInside != DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::ORDERPLACEMENTFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        //Sett::customers($SettlementId);
        Sett::settlement($UserExample->pid,$SettlementId,$settlementExample->money,$settlementExample->no);
        Result::success(ErrorEnum::PAYMENTSUCCESSFUL[$assemble->language]);
    }
    /**
     * TODO 兑换商品订单余额支付（灵龙积分、无忧积分）
     * @param $data pay_password address_id sku_id order_number remark
     * @return void
     */
    function exchangeOrderBalanceBuy($data){
        //Result::error("暂未开放接口");
        $assemble = Common::assemble(new ShopGoodsOrderExample(), $data);
        $pay_password=$data['pay_password'];
        $address_id=$data['address_id'];
        if($assemble->order_number <= DigitEnum::ZERO){
            Result::error(ErrorEnum::ILLEGALQUANTITY[$assemble->language]);
        }
        if($address_id <= DigitEnum::ZERO){
            Result::error(ErrorEnum::PLEASESELECTSHIPPINGADDRESS[$assemble->language]);
        }
        if($assemble->sku_id <= DigitEnum::ZERO){
            Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        }
        $conn = new Conn();
        $UserPassword = UsersModel::getUserPasswordInside($conn, $assemble->token);
        if($UserPassword["pay_password"] == null){
            Result::error(ErrorEnum::PLEASESETASECONDLEVELPAYMENTPASSWORD[$assemble->language]);
        }
        if($UserPassword["pay_password"] != md5(md5($pay_password))){
            Result::error(ErrorEnum::SECONDLEVELPAYMENTPASSWORDERROR[$assemble->language]);
        }
        $goodsSkuInfo = Common::assemble(new ShopGoodsSkuExample(),ShopGoodsSkuModel::getGoodsSkuInfo($conn, $assemble->sku_id));
        if($goodsSkuInfo->sku_stock < $assemble->order_number){
            Result::error(ErrorEnum::INSUFFICIENTINVENTORY[$assemble->language]);
        }
        $goodsSkuInfo->sku_stock = $goodsSkuInfo->sku_stock - $assemble->order_number;//减去库存
        if($goodsSkuInfo->sku_stock == 0){
            $goodsSkuInfo->sku_stock = '0';
        }
        $ShopGoodsExample = Common::assemble(new ShopGoodsExample(), ShopGoodsModel::getGoodsInfo($conn, $goodsSkuInfo->goods_id));
        if($ShopGoodsExample->is_top == DigitEnum::ZERO || $ShopGoodsExample->is_adopt == DigitEnum::ZERO){
            Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        }
        $UserExample = Common::assemble(new UserExample(), UsersModel::getUserInside($conn, $assemble->token));
        $assemble->merchant_id = $ShopGoodsExample->merchant_id;
        $assemble->goods_id = $ShopGoodsExample->goods_id;
        $assemble->order_price = $goodsSkuInfo->sku_sell_price;
        $userAddrExample = new UserAddrExample();
        $assemble->order_total_price = $goodsSkuInfo->sku_sell_price * $assemble->order_number;//支付金额
        $userAddrExample->id = $address_id;
        $assemble->member_id = $userAddrExample->uid = $UserExample->id;
        $assemble->type = DigitEnum::TWO;
        $userAddr = UsersAddrModel::getUserAddr($conn, $userAddrExample);
        if (!$userAddr){
            Result::error(ErrorEnum::DELIVERYADDRESSDOESNOTEXIST[$assemble->language]);
        }
        $balance = $UserExample->usdt - $assemble->order_total_price;
        if($assemble->order_total_price <= DigitEnum::ZERO || $UserExample->usdt <= DigitEnum::ZERO || $balance < DigitEnum::ZERO){
            Result::error(ErrorEnum::INSUFFICIENTBALANCE[$assemble->language]);
        }
        $assemble->receipt_name = $userAddr["name"];
        $assemble->receipt_phone = $userAddr["mobile"];
        $assemble->receipt_address = $userAddr["detailed_address"];
        $assemble->order_no ="dh".Utils::createOrderNo();
        $shopGoodsExample = new ShopGoodsExample();
        $shopGoodsExample->goods_id = $ShopGoodsExample->goods_id;
        $shopGoodsExample->sales_volume = $ShopGoodsExample->sales_volume + $assemble->order_number;
        $conn->shiwuStart();
        $insertShopGoodsOrderInside = ShopGoodsOrderModel::insertShopGoodsOrderInside($conn, $assemble);
        $upShopGoodsSkuInside = ShopGoodsSkuModel::upshopGoodsSkuInside($conn, $goodsSkuInfo);
        $editUserMoneyOutInside = UsersModel::editUserMoneyAndExchangeInside($conn, $assemble->order_total_price,$UserExample);
        $writeFundsMoney = Funds::writeFundsUsdt($conn, $UserExample->id, $assemble->order_no, FundsEnum::PROCURE, -$assemble->order_total_price, $balance, FundsEnum::PROCUREZHCN);
        $upShopGoodsInside = ShopGoodsModel::upShopGoodsInside($conn, $shopGoodsExample);
        if($insertShopGoodsOrderInside != DigitEnum::ONE || $upShopGoodsSkuInside != DigitEnum::ONE || $editUserMoneyOutInside != DigitEnum::ONE || $writeFundsMoney != DigitEnum::ONE || $upShopGoodsInside != DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::ORDERPLACEMENTFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::PAYMENTSUCCESSFUL[$assemble->language]);
    }
    /**
     * TODO 后台上单(返佣)
     * @param $data id capping
     * @return void
     */
    function crmBackendOrder($data){
        exit("已关闭");
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $UserExample = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $assemble->id));
        if($UserExample->id == null ){
            Result::error("未找到用户");
        }
        $settlementExample = new SettlementExample();
        $UserExample->language = 1;
        $cappingArr = [99,999,3999];
        if(!in_array($assemble->capping,$cappingArr)){
            Result::error("封顶值err");
        }
        $settlementExample->no = $assemble->order_no = Utils::createOrderNo();
        $settlementExample->uid = $UserExample->id;
        $settlementExample->money = $assemble->capping;
        $settlementExample->type = DigitEnum::TWO;
        $capping = max($assemble->capping, $UserExample->capping);
        $svip = 1;
        if($assemble->capping >= 999){
            $sn = date("Ymd", time());
            $winningNewCy = WinningModel::getWinningNewCy($conn, $sn, $UserExample->id);
            if(!$winningNewCy["number"] && $UserExample->level == DigitEnum::ZERO){
                $userExample2 = new UserExample();
                $userExample2->token = $UserExample->token;
                $userExample2->level = 1;
                UsersModel::upUserInside($conn, $userExample2);
            }
        }
        $conn->shiwuStart();
        $insertSettlementInside = SettlementModel::insertSettlementInside($conn, $settlementExample);
        $SettlementId = $conn->mysql_insert_id();
        $writeFundsMoney = Funds::writeFundsCrm($conn, $UserExample->id, $assemble->order_no, FundsEnum::BACKENDORDERPLACEMENT, $assemble->capping, DigitEnum::ZERO, FundsEnum::BACKENDORDERPLACEMENT);
        if($insertSettlementInside != DigitEnum::ONE || $writeFundsMoney != DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error("上单失败-1");
        }
        if($capping > $UserExample->capping){
            $editUserMoneyOutInside = UsersModel::editUserMoneyAndCappingInside($conn, 0,$capping,$svip,$UserExample);
            if($editUserMoneyOutInside != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error("上单失败-2");
            }
        }
        $conn->shiwuEnd();
        Sett::customers($SettlementId);
        Result::success("ok");
    }
}